<?php

namespace common\commands;


class Common
{

    static $iv = 'SupernovaSoftware';

    //加密key的密鑰
    public static function getSecretKey($system_type)
    {
        switch ($system_type) {
            default:
                $secretKey = '';
                break;
        }

        return $secretKey;
    }

    //生成key
    public static function generateCipherText($system_type, $datetime)
    {
        return trim(base64_encode(strtotime($datetime).'-'.$system_type));
        /*
        $dateString = $datetime . 'SS';
        $iv = substr(hash('sha384',self::$iv),0,16);
        $system_type = substr(hash('sha384',$system_type),0,31);
        $encrypted = openssl_encrypt($dateString, 'aes-256-cbc', $system_type, OPENSSL_RAW_DATA, $iv);

        return trim((base64_encode($encrypted)));
        */
    }


    //返回數據封裝
    public static function getPackedResponse($code, $message = null, $data = null)
    {

        $result['code'] = $code;
        if (isset($message))
            $result['message'] = $message;
        else
            $result['message'] = self::defaultMessage($code);

        $result['data'] = $data;

        return $result;
    }


    //默認錯誤信息獲取
    public static function defaultMessage($code)
    {
        switch ($code) {
            case MISSING_PARAMS:
                return \Yii::t('app', 'Missing parameters');
            case DATABASE_FAILED:
                return \Yii::t('app', 'data exception');
            case SUCCESS:
                return \Yii::t('app', 'success');
            default:
                return \Yii::t('app', 'Undefined');
        }
    }

    //驗證key是否合法
    public static function verifyCipherText($params)
    {

        // 判断参数是否为空
        if (!isset($params)) return false;
        // 判断参数是否为数组
        if (!is_array($params)) return false;
        // 判断是否有参数 system_type
        if (!array_key_exists('system_type', $params)) return false;
        $system_type = $params['system_type'];
        // 判断是否有参数 datetime
        if (!array_key_exists('timestamp', $params)) return false;
        $timestamp = $params['timestamp'];
        // 判断是否有参数 key
        if (!array_key_exists('key', $params)) return false;
        $key = $params['key'];

        // 当上述三个参数都为非空时
        if (!isset($system_type) || !isset($timestamp) || !isset($key)) return false;

        // 用base64解码 key，得到密文
        $cipherText = base64_decode($key);

        // 根据 system_type 获得密钥
        $secretKey = self::getSecretKey($system_type);

        // 用密钥解密密钥，获得明文
//        $plainText = openssl_decrypt($cipherText, 'aes-256-cbc', $secretKey, OPENSSL_RAW_DATA, $iv);
        $plainText = explode('-',$cipherText);
        // 如果解密成功，明文不为空

        if(!isset($plainText[0]) || $plainText[0] != $timestamp)
            return false;
        if(!isset($plainText[1]) || $plainText[1] != $secretKey)
            return false;

        // 校验明文的末尾两位是否为SS
//        $verificationContent = substr($plainText, -2);
//        if ($verificationContent != 'SS') return false;
        // 将明文的时间转为时间戳
//        $dateString = (string)substr($plainText, 0, -2);
        $verifyingTimestamp = $plainText[0];
        // 判断明文和加密时是否相等
//        dump($dateString);
//        dump($verifyingTimestamp);
//        dump($timestamp);
//        dump(strcasecmp($verifyingTimestamp, $timestamp));
        if (strcasecmp($verifyingTimestamp, $timestamp) != 0) return false;
        // 获取当前时间戳
        $currentDate = date_create()->getTimestamp();

//        dump($currentDate);
        // 计算差值
        $minute = floor($currentDate - $verifyingTimestamp) % 86400 / 60;

//        echo $minute;
//        die;
        if ($minute > 10) return false;

        return true;
    }


    //獲取2個時間的時間差
    public static function minutesBetween($endDate, $startDate)
    {
        $endDateString = (string)$endDate;
        $startDateString = (string)$startDate;

        $minute = floor($endDateString - $startDateString) % 86400 / 60;
        return $minute;
    }

    //生成登錄token
    public static function generateToken()
    {
        return str_replace('+', '-', base64_encode(md5(time().mt_rand(0, 1000),mt_rand(0, 1000))));
    }

    //生成identify_key
    public static function generateIdentifyKey()
    {
        return base64_encode(md5(time(), mt_rand(1000, 9999)));
    }

    //驗證手機驗證碼是否有效
    public static function valid_sms_code($code)
    {
        //測試暫時不驗證
        return true;

        /*
        $sms_code = IfoodSmsCode::findOne(['code'=>$code]);
        if($sms_code)
        {
            if(time()-$sms_code['expirestime'] > SMSCODE_TIME)
                return false;
            else
                return true;
        }else
        {
            return false;
        }
        */
    }
    /**
     * [md5pass 根据字符串生成md5加密后]
     * @Author   panwc
     * @DateTime 2017-10-12T10:36:27+0800
     * @param    [string]                   $pass [密码]
     * @param    [string]                   $salt [字符串]
     * @return   [string]                         [md5加密后加过]
     */
    public static function md5pass($pass,$salt){

        return md5(substr(md5($pass),0,10).$salt);

    }
    /**
     * [random_string 字符串随机生成]
     * @Author   panwc
     * @DateTime 2017-10-12T10:38:26+0800
     * @param    string                   $type [类型  alpha为大小写字母   alnum为字母+数字  munric为0-9     nozero为 1-9 ]
     * @param    integer                  $len  [长度]
     * @return   [string]                         [description]
     */
    public static function random_string($type = 'alnum', $len = 8)
    {
        switch($type)
        {
            case 'basic'    : return mt_rand();
                break;
            case 'alnum'    :
            case 'numeric'  :
            case 'nozero'   :
            case 'alpha'    :

                switch ($type)
                {
                    case 'alpha'    :   $pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                        break;
                    case 'alnum'    :   $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                        break;
                    case 'numeric'  :   $pool = '0123456789';
                        break;
                    case 'nozero'   :   $pool = '123456789';
                        break;
                }

                $str = '';
                for ($i=0; $i < $len; $i++)
                {
                    $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
                }

                return $str;
                break;
            case 'unique'   :
            case 'md5'      :

                return md5(uniqid(mt_rand()));
                break;

        }
    }
}

